/**
 * Created by Administrator on 2019/7/5.
 */
/**
 * Created by Administrator on 2019/5/22.
 */
var sysurl = "http://api.jyshfw.com/api/";
var weburl = "http://api.jyshfw.com";
var rootLink = document.location.toString();
var tmpsUrls = rootLink.split("www/")[0];
//var regHtml = /(<[a-z]+>)|(<\/[a-z]+>)|(<[a-z]+\sstyle="[^\"]*?">)|(<[a-z]+\sclass="[^\"]*?">)|(<[a-z]+\/>)|(<[a-z]+\sstyle="[^\"]*?"\/>)/;
var regHtml = /[^\x00-\xff]/g;

var data = window.location.href.substring(window.location.href.indexOf("?") + 1).split("#")[0].split('&');          //传入数据
var parameter = {};
data.map(function( item , index ){parameter[ item.split("=")[ 0 ] ] = item.split("=")[ 1 ];});


var postCfg = {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    transformRequest: function (data) {
        return $.param(data);
    }
};

var data = {};


// axios.defaults.baseURL = sysurl;
// axios.defaults.headers.post['Content-Type'] = 'application/json';
//
// Vue.config.productionTip = false

/**
 * 设置cookie
 * @param {type} name
 * @param {type} value
 * @returns {undefined}
 */
function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
}

/**
 * 获取cookie
 * @param {type} name
 * @returns {unresolved}
 */
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    }
    return null;
}

/**
 * 删除cookie
 * @param {type} name
 * @returns {undefined}
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval !== null)
        document.cookie = name + "=" + cval + ";path=/;expires=" + exp.toGMTString();
}

/**
 * 获取链接参数
 * @param {type} name
 * @returns {unresolved}
 */
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r !== null)
        return unescape(r[2]);
    return null;
}


/**
 * time : 60
 * self : this;
 * event 注册=register,修改手机号=changemobile,忘记密码：resetpwd
 * */
var timer,timeOff = true;

function sendTime(phone,event,self){
	var data = transFormData({mobile:phone,event:event});

    if( !/^1[3456789]\d{9}$/.test(phone) ){
        layer.msg("请输入正确手机号");
        return false;
    }
    if(self.time && self.timeOff){
        var tt = self.time;
        self.timeOff = false;
        axios.post(sysurl + 'sms/send',data).then( res => {
            if(res.data.code == 1){
                timer = setInterval(function(){
                    if(self.time > 0){
                        self.time --;
                    }else{
                        self.time = tt;
                        self.timeOff = true;
                        clearInterval(timer);
                        timer = null;
                    }
                },1000)
				layer.msg('短信发送成功')
            }else{
                layer.msg(res.data.msg);
            }
        })
    }
}
/**
 * 转换对象为form data
 * @data {需要转换为formdata的对象}
 */
function transFormData(data){
    var formData = new FormData();
    for(var key in data){
        formData.append(key,data[key])
    }
    return formData;
}

/**
 * 进入站点存入浏览历史
 * */
function inSite(site){
    var data = transFormData({
        user_id : getCookie("user_id"),
        token   : getCookie("token"),
        site_id : site.site_id
    })
    if(getCookie("token")){
        axios.post(sysurl + 'user/browseSiteLog' , data ).then(res => {
            var datas = res.data;
            if( datas.code === 1 ){
                console.log("进入站点成功,已存入浏览历史");
            }else{
                layer.msg(res.data.msg);
            }
        } , err => {}).catch(( error ) => {});
    }
}


axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
var index;
//添加请求拦截器
axios.interceptors.request.use(config => {
    //在发送请求之前做某事，比如说 设置loading动画显示
    index = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
    return config
}, error => {
    //请求错误时做些事
    return Promise.reject(error)
})

axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    var config = err.config;
    // If config does not exist or the retry option is not set, reject
    if(!config || !config.retry) return Promise.reject(err);

    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;

    // Check if we've maxed out the total number of retries
    if(config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(err);
    }

    // Increase the retry count
    config.__retryCount += 1;

    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, config.retryDelay || 1);
    });

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
        return axios(config);
    });
});

//添加响应拦截器
axios.interceptors.response.use(response => {
    //对响应数据做些事，比如说把loading动画关掉
    layer.close(index);
    if(response.data.code == 205){
        // setTimeout(function () {
        //     delCookie("token");
        //     window.location.href='login.html';
        // }, 3000);
    }
    return response
}, error => {
    //请求错误时做些事
    layer.close(index);
    return Promise.reject(error)
})

$(document).on('click','td img',(function (e) {
    //点击预览图片
    var src = e.target.src;
    layer.open({
        type       : 1 ,
        title      : false ,
        closeBtn   : 0 ,
        area       : [ '750px' , '500' ] ,
        skin       : 'layui-layer-nobg' ,
        shadeClose : true ,
        content    : '<img src="' + src + '" style="max-height:600px;max-width:100%;object-fit: contain">' ,
        scrollbar  : false
    });
}))


/***
 * 遍历fromdata对象
 */
function getFrom(data){
	let s = data.entries();
	for (let i=1;i<10;i++){
		console.log(s.next().value[0]+':'+s.next().value(1))
	}
}
